import { useNavigate, useLocation } from 'react-router-dom';
import { useState } from "react";
import { LoginService } from '../api/UserApi';
import './Login.css';
import CustomNotification from '../components/CustomNotification';

function Login() {
  const navigate = useNavigate();
  const location = useLocation();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [rememberMe, setRememberMe] = useState(false);
  const [notificationVisible, setNotificationVisible] = useState(false);
  const [notificationContent, setNotificationContent] = useState('');
  const handleLogin = async () => {
    if (username && password) {
      const userData = {
        "usernameOrEmail": username,
        "password": password,
      };
      const response = await LoginService(userData);
      if (response.status !== 200) {
        alert('登录失败，请重试');
        return;
      }
      setNotificationContent(`今日已签到成功`);
      setNotificationVisible(true); // 显示通知

      // 模拟服务器返回的 token
      const fakeToken = `${username}_${Date.now()}`;
      localStorage.setItem('token', fakeToken);
      localStorage.setItem('userId', response.data.id);
      if (rememberMe) {
        localStorage.setItem('username', username);
      }

      // 新增：在3秒后跳转页面
      setTimeout(() => {
        const from = location.state?.from || '/';
        navigate(from, { replace: true });
      }, 3000);
    }
  };

  return (
    <div className="login-container">
      <div className="login-box">
        <h2 className="login-logo-text">BT-7274</h2>
        <input
          type="text"
          placeholder="账号"
          value={username}
          onChange={e => setUsername(e.target.value)}
        />
        <input
          type="password"
          placeholder="密码"
          value={password}
          onChange={e => setPassword(e.target.value)}
        />
        <div className="remember-me">
          <input
            type="checkbox"
            checked={rememberMe}
            onChange={e => setRememberMe(e.target.checked)}
          />
          <label>记住我</label>
        </div>
        <button className="login-btn" onClick={handleLogin}>登录</button>
        <div className="bottom-links">
          <span>没有账号？</span>
          <button
            className="register-link"
            onClick={() => navigate('/register')}
          >
            去注册
          </button>
        </div>
        <div className="bottom-links">
        <button
            className="register-link"
            onClick={() => navigate('/admin')}
          >
            管理员登录
          </button>
        </div>
      </div>
      <CustomNotification 
        visible={notificationVisible} 
        title={notificationContent} 
        onClose={() => setNotificationVisible(false)} 
      />
    </div>
  );
}

export default Login;